package com.srit.source;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.srit.source.exception.SourceException;

/**
 * 按照dao中的.tem模板文件来替换来修改
 * 
 * @author guan
 * 
 */
public class GenerateSourceUtil extends Generate {

	static Logger log = LoggerFactory.getLogger(GenerateSourceUtil.class);

	public GenerateSourceUtil() {
		super();
	}

	/**
	 * 获取模板文件
	 * 
	 * @param fileList
	 * @return
	 */
	private File getTemFileInList(List fileList) {
		File templateDaoFile = null;
		for (Iterator<File> it = fileList.iterator(); it.hasNext();) {
			File tmp = it.next();
			if (tmp.getName().indexOf(TEMPLATE_SUFFIX) != -1) {
				templateDaoFile = tmp;
			}
		}
		return templateDaoFile;
	}

	/**
	 * @param templateFile
	 *            模板文件
	 * @param dirPath
	 *            目标目录
	 * @param beanName
	 *            实体名称
	 * @param fileType
	 *            dao，service 类型
	 * @throws SourceException
	 */
	private void createFile(String dirPath, String beanName, String fileType)
			throws SourceException {
		// try {
		List<File> fileListInDirPath = this.listFilesInDir(dirPath);
		File templateFile = this.getTemFileInList(fileListInDirPath);
		if (templateFile == null) {
			throw new SourceException(".tem 模板文件不存在");
		}

		File toFile = new File(dirPath + "/" + beanName + fileType
				+ JAVA_SUFFIX);
		// System.out.print(dirPath + "/" + beanName + fileType + JAVA_SUFFIX);
		try {
			BufferedReader reader = new BufferedReader(new FileReader(
					templateFile));
			if (!toFile.exists()) {
				BufferedWriter writer = new BufferedWriter(new FileWriter(
						toFile));
				String strLine = null;
				while ((strLine = reader.readLine()) != null) {
					writer.append(replaceStr(strLine, beanName));
					writer.append("\n");
				}
				reader.close();
				writer.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String replaceStr(String strLine, String beanName) {
		String result = strLine;
		if (strLine.indexOf("${Bean}") != -1) {
			result = strLine.replace("${Bean}", beanName);
		} else if (strLine.indexOf("${bean}") != -1) {
			result = strLine.replace("${bean}", beanName.substring(0, 1)
					.toLowerCase() + beanName.substring(1));
		} else if (strLine.indexOf("${modual}") != -1) {
			result = strLine.replace("${modual}", modual);
		} else {
			return result;
		}
		return replaceStr(result, beanName);
	}

	/**
	 * @param dirPath
	 * @param beanList
	 * @param fileType
	 * @throws SourceException
	 */
	public void createFilesByBeans(String dirPath, List<File> beanList,
			String fileType) throws SourceException {
		for (Iterator<File> it = beanList.iterator(); it.hasNext();) {
			File beanFile = it.next();
			String beanName = beanFile.getName().substring(0,
					beanFile.getName().lastIndexOf("."));
			createFile(dirPath, beanName, fileType);
		}
	}

	/**
	 * 生成Dao部分代码
	 * 
	 * @throws SourceException
	 */
	public void createDaoSource() throws SourceException {
		this.createFilesByBeans(this.daoPath, this.listBeansInPackage(),
				this.FILE_TYPE_DAO);
		this.createFilesByBeans(this.daoImplPath, this.listBeansInPackage(),
				this.FILE_TYPE_DAO_IMPL);
		log.debug("dao 代码生成结束");
	}

	/**
	 * 生成Service部分代码
	 * 
	 * @throws SourceException
	 */
	public void createServiceSource() throws SourceException {
		this.createFilesByBeans(this.servicePath, this.listBeansInPackage(),
				this.FILE_TYPE_SERVICE);
		this.createFilesByBeans(this.serviceImplPath,
				this.listBeansInPackage(), this.FILE_TYPE_SERVICE_IMPL);
		log.debug("service 代码生成结束");

	}

	/**
	 * 生成Action部分代码
	 * 
	 * @throws SourceException
	 */
	public void createActionSource() throws SourceException {
		this.createFilesByBeans(this.actionPath, this.listBeansInPackage(),
				this.FILE_TYPE_ACTION);
		log.debug("action 代码生成结束");
	}

	public static void main(String[] args) throws SourceException {
		GenerateSourceUtil gs = new GenerateSourceUtil();
		gs.setModual("migration");
		gs.createDaoSource();
		gs.createServiceSource();
		gs.createActionSource();
	}

}
